<?php
namespace app\index\logic;
use think\Db;
use Yansongda\Pay\Pay;

class Order
{
    /**
     * 生成订单号
     * @return string
     */
    public function generateOrderNumber()
    {
        $prefix = 'ORDA'; // 订单号前缀
        $timestamp = time(); // 当前时间戳
        $random = mt_rand(1000000, 9999999); // 随机数
        // 使用当前时间戳和随机数生成订单号
        $orderNumber = $prefix . $timestamp . $random;
        return $orderNumber;
    }

    /**
     * 获取支付号对象
     * @param $qid
     * @param $payType
     * @return array
     */
    public function getPaymentNumber($qid, $payType)
    {
        if ($payType == 1){
            $payment_id = Db::table('quick_app_info')->where('quick_id',$qid)->value('wx_payment_id');
        }else{
            $payment_id = Db::table('quick_app_info')->where('quick_id',$qid)->value('zfb_payment_id');
        }
        if (!$payment_id) {
            $where[] = ['is_default', '=', 1];
            $where[] = ['pay_mode', '=', $payType];
        } else {
            $where[] = ['id', '=', $payment_id];
        }

        $record = Db::table('quick_payment_number')->where($where)->findOrEmpty();
        return $record;
    }

    /**
     * 下单
     * @param $orderData
     * @param $paymentNumber
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function callPayment($orderData, $paymentNumber)
    {
        $contact = Db::table('quick_app_info')->where('quick_id',$orderData['quick_id'])->value('contact');
        if ($paymentNumber['pay_mode'] == 1) {
            //微信
            switch ($paymentNumber['payment_type']) {
                case 1:
                    //原生h5/app
                    return $this->wxCreateOrder($orderData, $paymentNumber, $contact);
                    break;
                case 2:
                    //米花h5
                    if($paymentNumber['pay_style'] == 1)
                    {
                        return $this->mhCreateOrder('WEIXIN', 'H5_WEIXIN', $orderData, $paymentNumber, $contact);
                    }else{
                        return $this->mhCreateOrder('WEIXIN', 'APP_WEIXIN', $orderData, $paymentNumber, $contact);
                    }

                    break;
                default:
                    return json(['code'=>101,'msg'=>'支付号类型异常']);
            }

        } elseif ($paymentNumber['pay_mode'] == 2) {
            //支付宝
            switch ($paymentNumber['payment_type']) {
                case 1:
                    //原生App
                    return $this->aliApp($orderData, $paymentNumber, $contact);
                    break;
                case 2:
                    //米花app/h5
                    if ($paymentNumber['pay_style'] == 1) {
                        $payType = 'ALIPAY_H5';
                    } else {
                        $payType = 'APP_ALIPAY';
                    }
                    return $this->mhCreateOrder('ALIPAY', $payType, $orderData, $paymentNumber, $contact);
                    break;
                default:
                    return json(['code'=>101,'msg'=>'支付号类型异常']);
            }
        } elseif ($paymentNumber['pay_mode'] == 3) {
            return $this->boost($orderData, $paymentNumber, $contact);
        }elseif ($paymentNumber['pay_mode'] == 4) {
            return $this->shopeePay($orderData, $paymentNumber, $contact);
        }
    }

    /**
     * 马来
     * @param $orderData
     * @param $paymentNumber
     * @return \think\response\Json
     * @throws \Exception
     */
    public function boost($orderData, $paymentNumber)
    {
        include_once('../extend/HwMiHuaApi/getSign.php');
        include_once('../extend/HwMiHuaApi/getData.php');
        $product[] = array(
            "sku" => "pwa充值",
            "price" => "{$orderData['total_fee']}",
            "productName" => "小说短剧充值",
            "quantity" => "1"
        );
        $inputOrderData = array(
            'merAccount'    => $paymentNumber['mer_account'],//商户标识
            'merNo'         => $paymentNumber['mer_no'],//商户编号
            'time'          => time(),//时间戳
            'orderId'       => $orderData['out_trade_no'],//订单号
            'amount'        => $orderData['total_fee'],//交易金额(分)
            'payWay'        => 'EWALLET',
            'userIp'        => $_SERVER['REMOTE_ADDR'],
            'productInfo'   => json_encode($product),
            'notifyUrl'     => $this->getNotifyUrl($paymentNumber), //后台回调地址
            'payType'       => 'MY_BOOST_URL', //支付类型
            'memberId'      => $orderData['uid'],
        );
        // 生成签名
        $privateKey = $paymentNumber['private_key'];
        $inputOrderData['sign'] = getMhSign($inputOrderData, $privateKey);
        $encodeData = encryptData($inputOrderData, $privateKey);
        $postData = array(
            'merAccount' => $paymentNumber['mer_account'], // 商户标识
            'data' => $encodeData
        );
        // 请求米花接口下单接口
        $api_url = "https://platformtest.xqdmipay.com/paygateway/mbpay/order/v1";
        $res = httpPost($api_url, http_build_query($postData));
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code'] == '000000') {
            $data['content']    = $res['data']['payUrl'];
            $data['ptype']      = 'h5';
            return json(['code'=>0,'msg'=>'success','data'=>$data]);
        } else {
            $LogLogic = \think\facade\App::model('Log', 'logic');
            $LogLogic->addInfo('mhCreateOrder', "paymentId:{$paymentNumber['id']},code:{$res['code']},msg:{$res['msg']}", $orderData['uid'], $orderData['quick_id']);
            return json(['code'=>102,'msg'=>'下单失败：' . $res['msg']]);
        }
    }

    /**
     * 新加坡
     * @param $orderData
     * @param $paymentNumber
     * @return \think\response\Json
     * @throws \Exception
     */
    public function shopeePay($orderData, $paymentNumber)
    {
        include_once('../extend/HwMiHuaApi/getSign.php');
        include_once('../extend/HwMiHuaApi/getData.php');
        $product[] = array(
            "sku" => "pwa充值",
            "price" => "{$orderData['total_fee']}",
            "productName" => "小说短剧充值",
            "quantity" => "1"
        );
        $inputOrderData = array(
            'merAccount'    => $paymentNumber['mer_account'],//商户标识
            'merNo'         => $paymentNumber['mer_no'],//商户编号
            'time'          => time(),//时间戳
            'orderId'       => $orderData['out_trade_no'],//订单号
            'amount'        => $orderData['total_fee'],//交易金额(分)
            'payWay'        => 'EWALLET',
            'userIp'        => $_SERVER['REMOTE_ADDR'],
            'productInfo'   => json_encode($product),
            'notifyUrl'     => $this->getNotifyUrl($paymentNumber), //后台回调地址
            'payType'       => 'SG_SHOPEEPAY', //支付类型
            'memberId'      => $orderData['uid'],
        );
        // 生成签名
        $privateKey = $paymentNumber['private_key'];
        $inputOrderData['sign'] = getMhSign($inputOrderData, $privateKey);
        $encodeData = encryptData($inputOrderData, $privateKey);
        $postData = array(
            'merAccount' => $paymentNumber['mer_account'], // 商户标识
            'data' => $encodeData
        );
        // 请求米花接口下单接口
        $api_url = "https://platform.mifapay.net/paygateway/mbpay/order/v1";
        $res = httpPost($api_url, http_build_query($postData));
        echo $res;die;
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code'] == '000000') {
            $data['content']    = $res['data']['payUrl'];
            $data['ptype']      = 'h5';
            return json(['code'=>0,'msg'=>'success','data'=>$data]);
        } else {
            $LogLogic = \think\facade\App::model('Log', 'logic');
            $LogLogic->addInfo('mhCreateOrder', "paymentId:{$paymentNumber['id']},code:{$res['code']},msg:{$res['msg']}", $orderData['uid'], $orderData['quick_id']);
            return json(['code'=>102,'msg'=>'下单失败：' . $res['msg']]);
        }
    }

    /**
     * 微信原生下单，支持：H5、App
     * @param $orderData
     * @param $paymentNumber
     * @param $contact
     * @return \think\response\Json
     */
    public function wxCreateOrder($orderData, $paymentNumber, $contact)
    {
        $order = [
            'out_trade_no'  => $orderData['out_trade_no'],
            'total_fee'     => $orderData['total_fee'],
            'body'          => '付费阅读' . $orderData['uid'] . '联系方式' . $contact,
        ];
        $wxConfig = [
            'appid'         => '', // APP APPID
            'app_id'        => '', // 公众号 APPID
            'miniapp_id'    => '', // 小程序 APPID
            'mch_id'        => '',
            'key'           => '',
            'notify_url'    => '',
            'cert_client'   => '', // optional, 退款，红包等情况时需要用到
            'cert_key'      => '',// optional, 退款，红包等情况时需要用到
            'log' => [ // optional
                'file'      => './logs/wechat.log',
                'level'     => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type'      => 'single', // optional, 可选 daily.
                'max_file'  => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout'   => 5.0,
                'connect_timeout' => 5.0,
                // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
            ]
        ];

        $wxConfig['mch_id']     = $paymentNumber['mch_id'];
        $wxConfig['key']        = $paymentNumber['apiv3'];
        $wxConfig['notify_url'] = $this->getNotifyUrl($paymentNumber);

        if ($paymentNumber['pay_style'] == 1) {
            $wxConfig['app_id'] = $paymentNumber['app_id'];
            $data['content']        = Pay::wechat($wxConfig)->wap($order)->getTargetUrl();
            $data['ptype'] = 'h5';
        } else {
            $wxConfig['appid']  = $paymentNumber['app_id'];
            $data['content']    = Pay::wechat($wxConfig)->app($order)->getContent();//微信app未测试过
            $data['ptype'] = 'app';
        }

        return json(['code'=>0,'msg'=>'success','data'=>$data]);
    }



    /**
     * 米花下单，支持：支付宝app、支付宝h5、微信h5
     * @param $payWay
     * @param $payType
     * @param $orderData
     * @param $paymentNumber
     * @param $contact
     * @return \think\response\Json
     */
    public function mhCreateOrder($payWay, $payType, $orderData, $paymentNumber, $contact)
    {
        include_once('../extend/MiHuaApi/config.php');
        include_once('../extend/MiHuaApi/getSign.php');
        include_once('../extend/MiHuaApi/getData.php');
        $inputOrderData = array(
            'merAccount'    => $paymentNumber['mer_account'],//商户标识
            'merNo'         => $paymentNumber['mer_no'],//商户编号
            'time'          => time(),//时间戳
            'orderId'       => $orderData['out_trade_no'],//订单号
            'amount'        => $orderData['total_fee'],//交易金额(分)
            'product'       => '付费阅读' . $orderData['uid'] . '联系方式' . $contact,
            'productDesc'   => '付费阅读' . $orderData['uid'] . '联系方式' . $contact,
            'attach'        => $orderData['uid'],
            'payWay'        => $payWay,
            'userIp'        => $_SERVER['REMOTE_ADDR'],
            'notifyUrl'     => $this->getNotifyUrl($paymentNumber), //后台回调地址
            'payType'       => $payType, //支付类型
        );
        // 生成签名
        $privateKey = $paymentNumber['private_key'];
        $inputOrderData['sign'] = getMhSign($inputOrderData, $privateKey);
        $encodeData = encryptData($inputOrderData, $privateKey);
        $postData = array(
            'merAccount' => $paymentNumber['mer_account'], // 商户标识
            'data' => $encodeData
        );
        // 请求米花接口下单接口
        $api_url = \MiHuaPayConfig::API_URL_CREATE_ORDER;
        $res = httpPost($api_url, http_build_query($postData));

        $res = json_decode($res, true);

        if (isset($res['code']) && $res['code'] == '000000') {
            if (in_array($payType, ['APP_ALIPAY','APP_WEIXIN'])) {
                $data['content']    = $res['data']['payInfo'];
                $data['ptype']      = 'app';
            } else {
                $data['content']    = $res['data']['payUrl'];
                $data['ptype']      = 'h5';
                $data['referer']    = $paymentNumber['referer'];
            }

            return json(['code'=>0,'msg'=>'success','data'=>$data]);
        } else {
            $LogLogic = \think\facade\App::model('Log', 'logic');
            $LogLogic->addInfo('mhCreateOrder', "paymentId:{$paymentNumber['id']},code:{$res['code']},msg:{$res['msg']}", $orderData['uid'], $orderData['quick_id']);

            return json(['code'=>102,'msg'=>'下单失败：' . $res['msg']]);
        }
    }

    /**
     * 返回回调地址
     * @param $paymentNumber
     * @return string
     */
    public function getNotifyUrl($paymentNumber)
    {
        $apiDomain = config('api_domain');
        if ($paymentNumber['pay_mode'] == 1 && $paymentNumber['payment_type'] == 1) {
            //微信原生
            return $apiDomain . "/index/notify/weChatNative/payId/{$paymentNumber['id']}";
        } elseif ($paymentNumber['payment_type'] == 2) {
            //米花
            return $apiDomain . "/index/notify/miHua";
        } elseif ($paymentNumber['pay_mode'] == 2 && $paymentNumber['payment_type'] == 1) {
            //支付宝原生
            return $apiDomain . "/index/notify/aliNative/payId/{$paymentNumber['id']}";
        } elseif ($paymentNumber['payment_type'] == 3) {
            //富友h5
            return $apiDomain . "/index/notify/fuYou";
        } else {
            throw new \Exception('支付号类型未知，获取回调链接失败');
        }
    }

}